import 'package:enterprise_v6_app/app/core/ext/ext.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/education_every_month_quiz_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/education_every_week_quiz_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/education_everyday_quiz_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/education_quiz_result_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/education_quiz_setting_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/education/quiz/model.dart';

extension _AnswerX on String {
  /// 'A;B' -> [0, 1]
  /// 'A' -> [0]
  List<int> get parseAnswers {
    return split(';').map((e) => e.codeUnitAt(0) - 65).toList();
  }
}

extension _QuizX on EducationEverydayQuizQuestionListOne {
  List<String> get options {
    final list = [
      optionA,
      optionB,
      optionC,
      optionD,
    ];
    list.removeWhere((e) => e.isBlankString);
    return list;
  }
}

extension _QuizX2 on EducationEverydayQuizQuestionList {
  List<String> get options {
    final list = [
      optionA,
      optionB,
      optionC,
      optionD,
    ];
    list.removeWhere((e) => e.isBlankString);
    return list;
  }
}

base class EduQuizIface {
  static Future<QuizConfig?> getEveryDayQuiz() async {
    final resp = await HttpUtil()
        .generateGetRequest<List<EducationEverydayQuizEntity>>(
          Interface.eduEverydayQuiz,
        )
        .execute(isShowLoading: true);
    final quizs = resp.data ?? [];
    if (quizs.isEmpty) {
      return null;
    }
    final topics = <QuizTopic>[];
    for (final item in quizs) {
      for (final item2 in item.questionListOne) {
        topics.add(QuizTopic(
          id: item2.id,
          question: item2.questionMain,
          answers: item2.questionValidity.parseAnswers,
          options: item2.options,
          score: item2.score,
          //explain: item2.explain,
        ));
      }
    }
    return QuizConfig(
      type: QuizType.dailyLearn,
      topics: topics,
    );
  }

  static Future<List<EducationEveryWeekQuizEntity>?> getEveryWeekQuiz() async {
    final resp = await HttpUtil().generateGetRequest<List<EducationEveryWeekQuizEntity>>(Interface.eduEveryWeekQuiz, queryParameters: {
      'planId': 1,
    }).execute(isShowLoading: true);
    return resp.data;
  }

  static Future<List<EducationEveryMonthQuizEntity>?> getEveryMonthQuiz() async {
    final resp = await HttpUtil().generateGetRequest<List<EducationEveryMonthQuizEntity>>(Interface.eduEveryMonthQuiz, queryParameters: {
      'planId': 2,
    }).execute();
    return resp.data;
  }

  static Future<QuizConfig?> getQuizById(String id, String planId) async {
    final resp = await HttpUtil().generateGetRequest<List<EducationEverydayQuizEntity>>(
      Interface.eduQuizList,
      queryParameters: {
        'id': id,
      },
    ).execute(isShowLoading: true);
    final quizs = resp.data ?? [];
    if (quizs.isEmpty) {
      return null;
    }
    final topics = <QuizTopic>[];
    for (final item in quizs) {
      for (final item2 in item.questionList) {
        topics.add(QuizTopic(
          id: item2.id,
          question: item2.questionMain,
          options: item2.options,
          score: item2.score,
          //explain: item2.explain,
        ));
      }
    }
    final setting = await quizSetting(id);
    return QuizConfig(
      type: QuizType.monthTest,
      topics: topics,
      textbookId: id,
      leftSeconds: (setting?.duration ?? 0) * 60,
      planId: planId,
    );
  }

  static Future<EducationQuizSettingEntity?> quizSetting(String textbookId) async {
    final resp = await HttpUtil().generateGetRequest<EducationQuizSettingEntity>(Interface.eduQuizSetting, queryParameters: {
      'textbookId': textbookId,
    }).execute();
    return resp.data;
  }

  static Future<void> submitQuiz(
    List<QuizTopic> topics,
    String textbookId,
    int seconds,
    String? planId,
  ) async {
    // time: 1:11:11
    final hour = (seconds ~/ 3600).toString().padLeft(2, '0');
    final minute = (seconds % 3600 ~/ 60).toString().padLeft(2, '0');
    final second = (seconds % 60).toString().padLeft(2, '0');
    final time = '$hour:$minute:$second';
    final data = topics
        .map((e) => {
              'id': e.id,
              'textbookId': textbookId,
              'planId': planId,
              'questionValidity': e.selectedIdx.map((e) => String.fromCharCode(65 + e)).join(';'),
              'timeCount': time,
            })
        .toList();
    final resp = await HttpUtil()
        .generatePostRequest<String>(
          Interface.eduQuizSubmit,
          data: data,
        )
        .execute(isShowLoading: true);
    final result = resp.data;
    if (result == null) {
      return;
    }

    final resp2 = await HttpUtil().generateGetRequest<EducationQuizResultEntity>(
      Interface.eduQuizResult,
      queryParameters: {
        'id': result,
      },
    ).execute();

    final result2 = resp2.data;
    if (result2 == null) {
      return;
    }

    for (final item in result2.questionList) {
      topics.where((element) => element.id == item.id).forEach((element) {
        element.explain = item.parsing;
        element.answers.clear();
        element.answers.addAll(item.questionValidity.parseAnswers);
      });
    }
  }

  /// {
  //   "id": "",
  //   "questionAnswerDTOList": [
  //     {
  //       "id": "",
  //       "planId": "",
  //       "questionValidity": "",
  //       "textbookId": "",
  //       "timeCount": ""
  //     }
  //   ],
  //   "recommendation": "",
  //   "surveyTypeIds": []
  // }
  static Future<void> submitDemandResearch(
      String? id,
      List<QuizTopic> topics,
      String? textbookId,
      int seconds,
      String? planId,
      List<String> surveyIds,
      String? recommendation,
      ) async {
    final hour = (seconds ~/ 3600).toString().padLeft(2, '0');
    final minute = (seconds % 3600 ~/ 60).toString().padLeft(2, '0');
    final second = (seconds % 60).toString().padLeft(2, '0');
    final time = '$hour:$minute:$second';
    final topicsData = topics
        .map((e) => {
      'id': e.id,
      'textbookId': textbookId,
      'planId': planId,
      'questionValidity': e.selectedIdx.map((e) => String.fromCharCode(65 + e)).join(';'),
      'timeCount': time,
    })
        .toList();
    final resp = await HttpUtil()
        .generatePostRequest<String>(
      '${Interface.mainBaseUrl}/education//educationSurvey/answer',
      data: {
        'id': id,
        'questionAnswerDTOList': topicsData,
        'recommendation': recommendation,
        'surveyTypeIds': surveyIds,
      },
    )
        .execute(isShowLoading: true);
    final result = resp.data;
    if (result == null) {
      return;
    }

    final resp2 = await HttpUtil().generateGetRequest<EducationQuizResultEntity>(
      Interface.eduQuizResult,
      queryParameters: {
        'id': result,
      },
    ).execute();

    final result2 = resp2.data;
    if (result2 == null) {
      return;
    }

    for (final item in result2.questionList) {
      topics.where((element) => element.id == item.id).forEach((element) {
        element.explain = item.parsing;
        element.answers.clear();
        element.answers.addAll(item.questionValidity.parseAnswers);
      });
    }
  }
}
